# app.py
# —— 极简图书管理系统（带可视化界面，无数据库） ——


from flask import Flask, request, redirect, url_for, render_template

# 1. 创建 Flask 应用
app = Flask(__name__)

# 2. 在内存中维护一本“图书”列表，结构：{"book_id": int, "title": str, "author": str, "is_borrowed": bool}
books = []
next_book_id = 1  # 自增 ID

# ---------- 路由与视图函数 ----------

@app.route('/', methods=['GET'])
def index():
    """
    主页：显示图书列表，并提供“添加新图书”表单
    """
    return render_template('index.html', books=books)


@app.route('/add', methods=['POST'])
def add_book():
    """
    添加新图书：接收表单 POST 数据
    表单字段：title, author
    """
    global next_book_id, books

    title = request.form.get('title', '').strip()
    author = request.form.get('author', '').strip()

    # 参数校验：title 和 author 不能为空
    if not title or not author:
        # 再次渲染主页，并传入错误提示
        return render_template('index.html', books=books, error="书名和作者不能为空")

    # 构造新图书对象
    book = {
        "book_id": next_book_id,
        "title": title,
        "author": author,
        "is_borrowed": False
    }
    books.append(book)
    next_book_id += 1

    # 添加完成后重定向回主页
    return redirect(url_for('index'))


@app.route('/borrow/<int:book_id>', methods=['POST'])
def borrow_book(book_id):
    """
    标记图书为“已借出”
    """
    for b in books:
        if b['book_id'] == book_id:
            b['is_borrowed'] = True
            break
    return redirect(url_for('index'))


@app.route('/return/<int:book_id>', methods=['POST'])
def return_book(book_id):
    """
    标记图书为“已归还”
    """
    for b in books:
        if b['book_id'] == book_id:
            b['is_borrowed'] = False
            break
    return redirect(url_for('index'))


@app.route('/delete/<int:book_id>', methods=['POST'])
def delete_book(book_id):
    """
    删除图书
    """
    global books
    # 通过列表推导式删除指定 book_id
    books = [b for b in books if b['book_id'] != book_id]
    return redirect(url_for('index'))


# ---------- 主程序入口 ----------
if __name__ == '__main__':
    # debug=True：代码有改动时自动重启
    app.run(host='0.0.0.0', port=5000, debug=True)
